// pages/order/order.js
let dateTimePicker = require('../../utils/dateTimePicker.js')
,that
,QQMapWX = require('../../utils/qqmap-wx-jssdk.js'),
qqmapsdk
,api = api = new(require('../../utils/api.js'))
,util = new (require('../../utils/util.js'));
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',district:'',city:'',phone:'',address:'',addressmore:'',recycletype:'',topublic:'',lat:'',lng:'',orderDate:'',
    dateTimeArray1: null,
    dateTime1: null,
    startYear: null,
    datestr:'',
    switchoaChecked:!1,
    endYear: null,
    address:'请选择收货地址',
    typeindex:0,
    weightindex:0,
    switchChecked:!1,
    oaindex:-1,
    btnloading:!1,
    oalist:[],
    jkindex:0,
    jkarr:[
      {id:-1,name:'是否是经济开发区订单'},
      {id:0,name:'否'},
      {id:1,name:'是'}
    ],
    weightarr:['10-25公斤','25-50公斤','50-250公斤','250公斤以上'],
    typearrs:[
      ['废旧纸箱','废旧书本','废旧报纸','废广告纸','废旧杂纸','低于15公斤废纸上门回收','需粉碎机'],
      ['废旧衣物'],
      ['废塑料瓶','杂塑料'],
      ['带皮铜线','铁皮类','不锈钢','铝'],
      ['废旧家电'],
      ],
    doortype:[
      {
        id:0,
        name:'尽快上门'
      },
      {
        id:1,
        name:'预约上门'
      },
    ],
    doortypeid:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    wx.showLoading({
      title: '加载中',
    })
    let {nowprice,user}=app.logininfo,{district}=user;//order_address=wx.getStorageSync('order_address'),
    // if(order_address){
    //   let {name,district,city,phone,address,addressmore,lat,lng} = order_address;
    //   that.setData({name,district,city,phone,address,addressmore,lat,lng})
    // }
   that.setData({districtid:district})
    
    api.getuserorder(res=>{
      if(res.data.issuccess==1){
        if(res.data.data){
          let {name,district,city,phone,address,addressmore,lat,lng} = res.data.data
          that.setData({name,district,city,phone,address,addressmore,lat,lng})
        }
      }
    })
    let tid=""
    that.setData({tid:options.tid,nowprice},()=>{
      api.Recycletypegetlister(that.data.tid,res=>{
        wx.hideLoading()
        if(res.data.issuccess==1){
          let oalist = res.data.oalist||[],oaarr = [];
          // if(oalist.length>0){
          //   oalist.forEach(x=>{ oaarr.push(x.name) })
          // }
          that.setData({typearr:res.data.list,oalist})
        }
      })
    })
    qqmapsdk = new QQMapWX({
      key: getApp().globalData.mapkey // 必填
    });
    // let {type}=options,typearr=this.data.typearrs[type]
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      // typestr:type==0?'PAPER':type==1?'CLOTH':type==2?'PLASTICS':type==3?'MATEL':'ELEC',
      // typearr,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });
  },
  toagreement(){
    wx.navigateTo({
      url: '../agreement/agreement',
    })
  },
  toprice(){
    wx.navigateTo({
      url: '../price/price',
    })
  },
  choseaddress(){
    if(that.data.switchoaChecked&&that.data.oaindex<0){
      util.nocancelmodal('请先选择经济开发区')
      return;
    }
    wx.chooseLocation({
     success:res=>{
       let {latitude,longitude,address,name} = res;
       console.log(res,'resres');
       qqmapsdk.reverseGeocoder({
        location:`${latitude},${longitude}`,
        success:res1=>{
          // console.log(res1.result.ad_info,'res1.result.ad_infores1.result.ad_info');
          
          let {district,city} = res1.result.ad_info;
          if(city=='东莞市')district='东莞市'
          wx.showLoading({
            title: '加载中',
          })
          if(!that.data.switchoaChecked){
            api.canorder({district,lat:latitude,lng:longitude},res=>{
              wx.hideLoading()
              if(res.data.issuccess==1){              
                // let{province,city} = res1.result.ad_info;
                that.setData({ lat: latitude, lng: longitude, district,city, address:name, erraddress:!1})
              }else{
              //  util.nocancelmodal('该地区暂无配送')
              that.setData({erraddress:!0})
              wx.showModal({
                title: '提示',
                content:'该区域暂未开通服务',
                confirmText:'申请开通',
                success:res=>{
                  if(res.confirm){
                    wx.navigateTo({
                      url: '../memberapply/memberapply',
                    })
                  }
                }
              })
              }
            })
          }else{
            
            wx.hideLoading()
            that.setData({ lat: latitude, lng: longitude, district,city, address:name, erraddress:!1})
          }

          // console.log('qqmapsdkres',res1);
          
        }
       } 
       )
       
       
     },
     complete:(res)=>{
        console.log('complete',res);
        
     }
    })
  },
  switch1Change(e){
    console.log('switch1Change',e);
    that.setData({switchChecked:e.detail.value})
    
  },
  switchoaChange(e){
    // if(Number(e.detail.value)==1||Number(e.detail.value)==0){
    //   that.setData({oaindex:-1})
    // }
   that.setData({jkindex:Number(e.detail.value)})
    
  },
  changeDateTime1(e) {

    this.setData({
      dateTime1: e.detail.value
    });
  },
  bindtypeChange(e){
    that.setData({typeindex:e.detail.value})

  },
  bindoaChange(e){
    
    that.setData({oaindex:e.detail.value})

  },
  bindweightChange(e){
    that.setData({weightindex:e.detail.value})

  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
   // let datestr = `${dateArr[0][arr[0]]}-${dateArr[1][arr[1]]}-${dateArr[2][arr[2]]} ${dateArr[3][arr[3]]}:${dateArr[4][arr[4]]}`


    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
     // datestr

    });
  },
  // radioChange(e){
  //   let {value}=e.detail
  //   that.setData({
  //     doortypeid:value
  //   })
  // },
  doortime(e){
    console.log(e.currentTarget.dataset,'eeeeee');
    that.setData({
      doortypeid:e.currentTarget.dataset.code
    })
  },
  input(e){
    that.setData({
      [e.currentTarget.dataset.prop]:e.detail.value
    })
  },
  save(){
    if(that.data.switchoaChecked&&that.data.oaindex<0){
      util.nocancelmodal('请先选择经济开发区')
      return;
    }
    that.setData({btnloading:!0})
    if (that.data.erraddress==true){
      wx.showModal({
        title: '提示',
        content: '该区域暂未开通服务',
        confirmText: '申请开通',
        success: res => {
          if (res.confirm) {
            wx.navigateTo({
              url: '../memberapply/memberapply',
            })
          }
        }
      })
      return;
    }
    //ts 下单时间戳 毫秒
    let 
      { dateTimeArray1,jkindex,districtid, dateTime1, name,oaindex, district, city,phone, address, addressmore, lat, lng, switchChecked, typearr, typeindex, tid, weightindex, doortypeid} = this.data,type=tid,
    recycletype=typearr[typeindex].id,
    topublic=switchChecked==true?'1':'0',err = '',
    timearr =`${dateTimeArray1[0][[dateTime1[0]]]}-${dateTimeArray1[1][[dateTime1[1]]]}-${dateTimeArray1[2][[dateTime1[2]]]} ${dateTimeArray1[3][[dateTime1[3]]]}:${dateTimeArray1[4][[dateTime1[4]]]}:00`,orderDate = new Date(timearr).getTime(),
      data = { districtid,name,orderDate,district,city,phone,address,addressmore,recycletype,topublic,lat,lng,type,doortype:doortypeid,weightsection:Number(weightindex)+1};
    let order_address={name,district,city,phone,address,addressmore,lat,lng}
    if (doortypeid!=1){
      data['orderDate'] = new Date().getTime();
    }
    if(oaindex>-1){
      data['oaid'] = that.data.oalist[oaindex].id
    }
    console.log(district,'district');
    
    if(district.length==0) err = "请选择收货地址"
    if(addressmore.length==0) err = "请填写详细地址"
    if(phone.length==0) err = "联系电话不能为空"
    if(name.length==0) err = "姓名不能为空"
    if(doortypeid==1){
      if(new Date(timearr)-new Date()<0)  err = "预约时间错误"
    }
    if(that.data.oalist.length>0){
      if(jkindex==0)err = "请选择是否是经济开发区"
      if(jkindex==2&&oaindex==-1)err = "请选择经济开发区"
    }
    if(err.length>0){
      that.setData({btnloading:!1})
      wx.showModal({
        title: '提示',
        showCancel:!1,
        content:err
      })
      return;
    }
    console.log(data,'datatatata');
    api.addorder(data,res=>{
      that.setData({btnloading:!1})
      if(res.data.issuccess==1){
        util.nocancelmodal('下单成功！',"",res=>{
          wx.setStorageSync('order_address',order_address)
          wx.navigateBack()
          })
      }else{
        util.nocancelmodal(res.data.msg)
      }
    })

    // util.nocancelmodal('功能逻辑修改中',"",res=>{
    // })
    

    // 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})